
package cc.md888.app.application.activatecode;

import cc.md888.app.exception.BizRuntimeException;
import cc.md888.result.ResultCode;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalNotification;
import jakarta.mail.AuthenticationFailedException;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Store;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Author: o_liuwei837
 * Description:
 * Date: 2024/9/2 16:01
 */
@Slf4j
public class AbstractMailServerConnectionPool {

    private Map<String , Session> mailServerMap = new ConcurrentHashMap<>();


    private Cache<String, Store> mailStoreCache = CacheBuilder.newBuilder()
            .expireAfterAccess(1, TimeUnit.MINUTES)
            .removalListener(this::closeStore)
            .build();



    public Session getSession(String email){
        if(mailServerMap.containsKey(email)){
            return mailServerMap.get(email);
        }else{
            Properties properties = getMailServer(email);
            Session session = Session.getDefaultInstance(properties);
            mailServerMap.put(email, session);
            return session;
        }
    }

    public Store getStoreCache(String email, String password) throws MessagingException {
        Store store = mailStoreCache.getIfPresent(email);
        if(store == null){
            store = getStore(email, password);
        }

        return store;
    }


    public Store getStore(String email, String password) throws  MessagingException {
        Session session = getSession(email);
        Store store = session.getStore();
        if(!store.isConnected()){
//            log.info("Connect email store host: {}" , host );
            store.connect( email, password);
        }
        return store;
    }


    public Properties getMailServer(String email){
        throw BizRuntimeException.from(ResultCode.ERROR, "不支持的邮箱：" + email);
    }

    /**
     * 检查邮箱是否存活
     * @param email
     * @param password
     * @return true email is expire , false no expire,
     */
    public Boolean isAlive(String email, String password){
        try {
            Store store = getStore(email, password);
            return true;
        }catch (AuthenticationFailedException e){
            return false;
        } catch (Exception e) {
            return null;
        }
    }

    protected static String parseEmailDomain(String email){
        if (StringUtils.isEmpty(email)) {
            return "outlook.com";
        }

        int atIndex = email.indexOf("@");
        if(atIndex == -1){
            return null;
        }

        return email.substring(atIndex  + 1);
    }



    private void closeStore(RemovalNotification<String, Store> notification){
        try {
            Store store = notification.getValue();
            log.info("Close mail store: {}" , store.getURLName());
            store.close();
        } catch (Exception e) {
            log.info("Close mail err: ", e);
        }
    }


//    public static void main(String[] args) throws MessagingException, InterruptedException, IOException {
//        AbstractServerConnectionPool pool = new AbstractServerConnectionPool();
//
//        //in021p319pt@hotmail.com,L0uraLnSM
//        //ck3kq9jspjk@outlook.com,fyzFsAugft
//        //r7pos945870@hotmail.com,v5LGyLWRFu1yP
//        //RalphNelson2016189@hotmail.com y2XWhuTNzA
//        String email = "TerrySanders1994853@hotmail.com";
//        String password = "EwBIA+l3BAAUcDnR9grBJokeAHaUV8R3+rVHX+IAAR/pMnS0sHEih9rMKlzmZhxWW7KZB+4/ujmtCD0k5DwvOQBY484tvkW0+Ib8qTYjwEGbIIdkUngTo//jz+7hiwlzHIQQcfN4g/8POHd2BP9q0iB99P/VjYZv9M4A4d369A9BxW/20yt+B6T3MyH3ykh+lOpkwaxMvLNumJogJutTdE/UXKo9bXonqMTnbP3xjBlKjhi5whfGxGazsIKR+S7pWEuUECD6D/GzxKJJU1GByLObMv9UHmaiBr44GT6gX79axylohbpKt/YPHTRULFa2Qk/uQBr23k4CF0N1bjjmc4imyn6yUKDkfvksMxiO6NwGE14NdGEmhfEr58IjSY8QZgAAEI45tPrBtnp21hvSNVel95wQAjYf7e0mULvRU+rKAR5kRZc/oC7hKjPsfWNavWRXOr/H1buPSAQCrk29BTr2LDn1X2i5YyYvcS71MfCCiXvbJFHsByZCrKDHLcFVYzd7bEFRqWPdICS3jsFAmKWzqdZ5WBogdME3cFmbxuX6zcsoKb2I6E3oofwBC9jNY88CZbrk41BQ2l2U4hpmV+kTKxc1VTtdaMLomoy9zPL0RwpS8S2NkkppdbdQAdXvyYiPqNdTW0untWPojOvziggUZn4kCU9NFs7h0nskrmmOprs13IaiM599uF01mDXpgMOAGcOZ9UdWt1DntdEyjR4uv4sxnnGzAGqDSjvonMFemWIRF0+xeiR3mWp3oRJMsVlWQSrn2uLiBuRiiHLrqbPA7M1mY814PwmUovO32Q1QPGa+jtM40PXC4lnI5K7d+mZfTSyNqpZy/9AwjYIGpZiWZh6sRRenwGAn/qFyFqYUhzQT8+q7ifY2qPdC5zWG1KUN1sNPVBj0sVMQOVPJa2w5Th96ZIR3/8rP8K0n8aQdqFBTpaZlVhIRpe5sf/01fA55VD+nzs1cw5X0lFaj+7fIyPZxnbaX9apcyjMLqkpsVseWgA43NE49ImEN6QpLEemycr2gRT6vks36u5W95idfmOOyNfDs3Syil6ZOBXkTwOLLo8sawes5YGaHppxEi6F81uJywjt5I+i9ty/Iq5Jj47PxS00C";
//
//        //base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")
////        password = Base64.getEncoder().encodeToString(("user=" + email + "^Aauth=Bearer " + password + "^A^A").getBytes(StandardCharsets.UTF_8));
//        Store store = pool.getStoreCache(email, password);
//        //in021p319pt@hotmail.com,L0uraLnSM
////        pool.getStoreCache("in021p319pt@hotmail.com", "L0uraLnSM").getFolder("INBOX").open(Folder.READ_ONLY);
//
//        log.info("Start check email : {}", email);
//        // 打开收件箱
//        Folder inbox = store.getFolder("INBOX");
//        inbox.open(Folder.READ_ONLY);
//        int unreadCount = Math.min(inbox.getUnreadMessageCount(), 10);
//        int messageCount = inbox.getMessageCount();
//        if (unreadCount > 0) {
//            // 获取邮件列表
//            Message[] messages = inbox.getMessages(Math.max(1, messageCount - unreadCount), messageCount);
//            // 遍历邮件并下载EML格式的邮件
//            ArrayUtils.reverse(messages);
//            for (Message message : messages) {
//                String subject = message.getSubject();
//                Address from = message.getFrom()[0];
//                String fromEmail = Objects.equals(from.getType(), "rfc822") ? ((InternetAddress) from).getAddress() : from.toString();
////                if (message.isSet(Flags.Flag.SEEN)) {
////                    continue;
////                }
//
//
//                log.info("邮箱：{}，收到新邮件，发件人：{}，邮件主题：{}", email , fromEmail, subject);
//                log.info("邮件内容：{}", IMAPMailService.extractContentAsString(message.getContent(), "text/plain"));
//                log.info("邮件验证码：{}", EmailActivateService.extractEmailCode(email, fromEmail, IMAPMailService.extractContentAsString(message.getContent(), "text/plain")));
//
//            }
//        }
//    }
}
